package com.tanxi521.springboot.task;

import com.tanxi521.springboot.mapper.PlayerAccountMapper;
import com.tanxi521.springboot.mapper.RewardRecordMapper;
import com.tanxi521.springboot.pojo.OnlinePlayer;
import com.tanxi521.springboot.service.OnlinePlayerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: i-xiaotian
 * @Date: 2022/4/10 1:29
 * @EMAIL: 1254806967@qq.com
 */
@Component
@Slf4j
public class TaskManager {

    @Value("${task.on}")
    private boolean open;

    @Autowired
    PlayerAccountMapper playerAccountMapper;

    @Autowired
    OnlinePlayerService onlinePlayerService;

    @Autowired
    RewardRecordMapper rewardRecordMapper;

    @Scheduled(cron = "0 0/15 * * * *")
    public void recordPlayerOnline() {
        if (!open) return;
        int count = playerAccountMapper.selectPlayerOnlineCount();
        Date numTime = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long time = numTime.getTime();
        OnlinePlayer onlinePlayer = new OnlinePlayer();
        onlinePlayer.setPlayerCount(count);
        onlinePlayer.setTime(time+"");
        onlinePlayerService.insert(onlinePlayer);
        log.info("已保存 " + format.format(numTime) + " 在线人数: " + count);
    }

    @Scheduled(cron = "15 0 0 * * ?")
    public void updatePerDayRewards() {
        if (!open) return;
        int i = rewardRecordMapper.deleteWhereTimeToUpdatePerDay();
        log.info("每日礼包刷新，已删除 " + i + " 条昨日数据");
    }

    @Scheduled(cron = "5 0 0 * * 0")
    public void updatePerWeekRewards() {
        if (!open) return;
        int i = rewardRecordMapper.deleteWhereTimeToUpdatePerWeek();
        log.info("每周礼包刷新，已删除 " + i + " 条上周数据");
    }
}
